import ProductCard, { ProductCardSkeleton } from "@/src/components/ProductCard";
import { Button } from "@/src/components/ui/button";
import prisma from "@/src/db/db";
import { cache } from "@/src/lib/cache";
import { ArrowRight } from "lucide-react";
import Link from "next/link";
import React, { Suspense } from "react";

const getMostPopularProducts = cache(
  () => {
    return prisma.product.findMany({
      where: {
        isAvailableForPurchase: true,
      },
      orderBy: {
        orders: {
          _count: "desc",
        },
      },
      take: 6,
    });
  },
  ["/", "getMostPopularProducts"],
  { revalidate: 60 * 60 * 24 }
);

const getNewestProducts = cache(
  () => {
    return prisma.product.findMany({
      where: {
        isAvailableForPurchase: true,
      },
      orderBy: {
        createAt: "desc",
      },
      take: 6,
    });
  },
  ["/", "getNewestProducts"],
  { revalidate: 60 * 60 * 24 }
);

async function ProductSuspense({ productsFetcher }) {
  const products = await productsFetcher();
  return products.map((product) => {
    return <ProductCard key={product.id} {...product} />;
  });
}

const ProductGridSection = ({ productsFetcher, title }) => {
  return (
    <div className="space-y-4">
      <div className="flex gap-4">
        <h2 className="text-3xl font-bold">{title}</h2>
        <Button variant="outline" asChild>
          <Link href="/products" className="space-x-2">
            <span>View All</span>
            <ArrowRight className="size-4" />
          </Link>
        </Button>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
        <Suspense
          fallback={
            <>
              {new Array(6).fill(null).map((_, i) => {
                return <ProductCardSkeleton key={i} />;
              })}
            </>
          }
        >
          <ProductSuspense productsFetcher={productsFetcher} />
        </Suspense>
      </div>
    </div>
  );
};

const Page = () => {
  return (
    <main className="space-y-12">
      <ProductGridSection
        title="Most Popular"
        productsFetcher={getMostPopularProducts}
      />
      <ProductGridSection title="Newest" productsFetcher={getNewestProducts} />
    </main>
  );
};

export default Page;
